
#include "RayTracing.h"


bool TraceLine(const float orig[3], const float dir[3], const float* tri, float* dist){

	float E1[3], E2[3], T[3], Q[3], P[3];
	float det, inv_det, u, v, t;

	E1[0] = tri[3] - tri[0];
	E1[1] = tri[4] - tri[1];
	E1[2] = tri[5] - tri[2];

	E2[0] = tri[6] - tri[0];
	E2[1] = tri[7] - tri[1];
	E2[2] = tri[8] - tri[2];

	my_cross(P, -dir, E2);

	det = dot(P, E1);

	if((det < 0.00001) && (det > -0.00001))
		return false;

	T[0] = orig[0] - tri[0];
	T[1] = orig[1] - tri[1];
	T[2] = orig[2] - tri[2];

	inv_det = 1.0f/det;

	u = dot(P, T) * inv_det;

	if( (u < 0) || (u > 1))
		return false;

	my_cross(Q, T, E1);

	float n_dir[3] = {-dir[0], -dir[1], -dir[2]};
	v = dot(Q, n_dir) * inv_det;

	if( (v < 0) || (u + v > 1))
		return false;

	t =  -0.95f * dot(Q, E2) * inv_det;

	if(t < 0)
		return false;

	*dist = t;

	return true;

}

